package com.gnrsoft.rpc.client;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.UUID;

import com.gnrsoft.rpc.common.RpcRequest;
import com.gnrsoft.rpc.common.RpcResponse;
import com.gnrsoft.rpc.registry.ServiceDiscovery;

public class RpcInvocationHandler implements InvocationHandler {

	private ServiceDiscovery serviceDiscovery;

	private String serverAddress;

	public RpcInvocationHandler(ServiceDiscovery serviceDiscovery) {
		this.serviceDiscovery = serviceDiscovery;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

		String requestId = UUID.randomUUID().toString();

		RpcRequest rpcRequest = new RpcRequest(requestId, method.getDeclaringClass().getName(), method.getName(),
				method.getParameterTypes(), args);

		// 每次客户端调用的时候去发现服务
		if (serviceDiscovery != null) {
			serverAddress = serviceDiscovery.discover();
		}

		String[] serverAddressArray = serverAddress.split(":");

		RpcClient rpcClient = new RpcClient(serverAddressArray[0], Integer.parseInt(serverAddressArray[1]));

		// rpc调用 执行method，返回结果
		RpcResponse rpcResponse = rpcClient.send(rpcRequest);

		if (rpcResponse.isError()) {
			throw rpcResponse.getError();
		} else {
			return rpcResponse.getResult();
		}

	}

}
